package handler

import (
	"context"
	"go.uber.org/zap"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	"sale_system/userop_srv/global"
	"sale_system/userop_srv/model"
	"sale_system/userop_srv/proto"
)

type UserFavServer struct {
	proto.UnimplementedUserFavServer // 一定需要实现这个接口
}

func (s *UserFavServer) mustEmbedUnimplementedGoodsServer() {
	//TODO implement me
	panic("implement me")
}

func (s *UserFavServer) GetFavList(ctx context.Context, request *proto.UserFavRequest) (*proto.UserFavListResponse, error) {

	var rsp proto.UserFavListResponse
	var userFavs []model.UserFav
	var userFavList []*proto.UserFavResponse
	//查询用户的收藏记录
	//查询某件商品被哪些用户收藏了
	result := global.DB.Where(&model.UserFav{User: request.UserId}).Find(&userFavs)
	if result.RowsAffected == 0 {
		zap.S().Info("用户收藏列表为空")
		return nil, status.Error(codes.NotFound, "找不到用户收藏列表")
	}
	//result := global.DB.Where("user = ? and goods = ?", request.UserId, request.GoodsId).Find(&userFavs)
	rsp.Total = int32(result.RowsAffected)

	for _, userFav := range userFavs {
		userFavList = append(userFavList, &proto.UserFavResponse{
			UserId:  userFav.User,
			GoodsId: userFav.Goods,
		})
	}

	rsp.Data = userFavList

	return &rsp, nil
}
func (s *UserFavServer) AddUserFav(ctx context.Context, request *proto.UserFavRequest) (*emptypb.Empty, error) {

	FavInfo := model.UserFav{
		User:  request.UserId,
		Goods: request.GoodsId,
	}
	global.DB.Save(&FavInfo)
	return &emptypb.Empty{}, nil
}
func (s *UserFavServer) DeleteUserFav(ctx context.Context, request *proto.UserFavRequest) (*emptypb.Empty, error) {

	if result := global.DB.Unscoped().Where("goods=? and user=?", request.GoodsId, request.UserId).Delete(&model.UserFav{}); result.RowsAffected == 0 {
		zap.S().Info("收藏记录不存在")
		return nil, status.Errorf(codes.NotFound, "收藏记录不存在")
	}
	return &emptypb.Empty{}, nil
}
func (s *UserFavServer) GetUserFavDetail(ctx context.Context, request *proto.UserFavRequest) (*emptypb.Empty, error) {

	// 还不知道怎么改，等看前端再决定
	var userFav model.UserFav
	if result := global.DB.Where("goods=? and user=?", request.GoodsId, request.UserId).Find(&userFav); result.RowsAffected == 0 {
		zap.S().Info("收藏记录不存在")

		return nil, status.Errorf(codes.NotFound, "收藏记录不存在")
	}
	return &emptypb.Empty{}, nil
}
